package com.hmy.pig.service;

import cn.hutool.core.io.FileUtil;
import cn.hutool.extra.qrcode.QrCodeException;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hmy.pig.domain.HmyPig;
import com.ruoyi.common.core.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.util.Objects;


/**
 * @author yyh
 * @date 2024/2/20 16:41
 * @description QrCodeService
 */
@Service
public class QrCodeService {
    @Autowired
    private QrConfig config;

    @Autowired
    private TencentCOS tencentCOS;

    //生成到文件
    public void createCodeToFile(String content, String filePath) {
        try {
            QrCodeUtil.generate(content,config, FileUtil.file(filePath));
        } catch (QrCodeException e) {
            e.printStackTrace();
        }
    }
    //生成到流
    public byte[] createCodeToStream(String content) {
        try {
            return QrCodeUtil.generatePng(content, config);
        } catch (QrCodeException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void upload(HmyPig hmyPig){
        JSONObject jsonObj = (JSONObject) JSON.toJSON(hmyPig);
        String jsonStr = jsonObj.toString();
                /*
                上传文件
                 */
        String url = tencentCOS.upLoad(
                        /*
                        生成二维码
                         */
                new ByteArrayInputStream(createCodeToStream(jsonStr)),
                hmyPig.getPigCode()
        );
        if (Objects.isNull(url) || "".equals(url)){
            throw new ServiceException("主机异常");
        }
        hmyPig.setCodeUrl(url);
    }

}
